<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 写攻略的弹窗 -->
    <el-dialog
        v-model="showWriteGuide"
        title="写攻略"
        width="80%"
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
      <div class="space-y-6">
        <!-- 标题输入 -->
        <el-input
            v-model="newGuide.title"
            placeholder="请输入攻略标题"
            class="text-lg"
            maxlength="50"
            show-word-limit
        />
        <!-- 基础信息 -->
        <div class="grid grid-cols-3 gap-4 mb-4">
          <el-select v-model="newGuide.destination" placeholder="选择目的地" class="w-full">
            <el-option label="云南大理" value="云南大理"/>
            <el-option label="云南丽江" value="云南丽江"/>
            <el-option label="云南昆明" value="云南昆明"/>
          </el-select>
          <el-select v-model="newGuide.travelDays" placeholder="行程天数" class="w-full">
            <el-option v-for="i in 10" :key="i" :label="`${i}天`" :value="i"/>
          </el-select>
          <el-select v-model="newGuide.tripType" placeholder="旅行类型" class="w-full">
            <el-option :label="'文化探索'" :value="1"/>
            <el-option :label="'美食之旅'" :value="2"/>
            <el-option :label="'户外探险'" :value="3"/>
          </el-select>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <el-date-picker
              v-model="newGuide.departureDate"
              type="date"
              placeholder="出发日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              class="w-full"
          />
          <el-select v-model="newGuide.numberOfTravelers" placeholder="出行人数" class="w-full">
            <el-option v-for="i in 10" :key="i" :label="`${i}人`" :value="i"/>
          </el-select>
          <el-select v-model="newGuide.budgetRange" placeholder="预算范围" class="w-full">
            <el-option label="2000以下" value="2000以下"/>
            <el-option label="2000-5000" value="2000-5000"/>
            <el-option label="5000-10000" value="5000-10000"/>
            <el-option label="10000以上" value="10000以上"/>
          </el-select>
        </div>
        <!-- 描述输入 -->
        <el-input
            v-model="newGuide.description"
            type="textarea"
            placeholder="请输入简短的攻略描述"
            maxlength="200"
            show-word-limit
            rows="3"
            class="mt-4"
        />
        <!-- 封面图片上传 -->
        <el-form-item>
          <el-upload class="avatar-uploader"
                     :action="`${SERVER_ADDR}/scenicSpot/upload`"
                     name="pic"
                     :headers="headers"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <span class="ml-1">上传封面图片</span>
          </el-upload>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <div style="border: 1px solid #ccc; margin-bottom: 5px;">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
          />
          <el-form-item label="内容">
            <QuillEditor v-model="newGuide.content"/>
          </el-form-item>
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end gap-4">
          <el-button @click="handleClose" class="!rounded-button">取消</el-button>
          <el-button type="primary" @click="handleSubmit" class="!rounded-button">发布攻略</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="min-h-screen bg-gray-50">
      <!-- 顶部导航 -->
      <nav class="fixed top-0 left-0 right-0 h-16 bg-white shadow-sm z-50">
        <div class="max-w-7xl mx-auto px-4 h-full flex items-center justify-between">
          <div class="flex items-center gap-4">
            <el-icon class="text-gray-600 text-xl cursor-pointer">
              <ArrowLeft/>
            </el-icon>
            <h1 class="text-lg font-medium">旅行攻略</h1>
          </div>
          <div class="flex items-center gap-4">
            <el-button type="primary" class="!rounded-button" @click="showWriteGuideDisalog()">写攻略</el-button>
          </div>
        </div>
      </nav>
      <!-- 主要内容区域 -->
      <div class="max-w-7xl mx-auto px-4 pt-24 pb-16">
        <!-- 标题区域 -->
        <div class="bg-white rounded-lg p-6 mb-6">
          <div class="flex items-start justify-between">
            <div class="flex-1">
              <h1 class="text-2xl font-bold mb-4">{{ guideData.title }}</h1>
              <div class="flex items-center gap-3">
                <img :src="`${SERVER_ADDR}/category/pic/${guideData.user.avatar}`" class="w-10 h-10 rounded-full object-cover"/>
                <div>
                  <p class="font-medium">{{ guideData.user.username }}</p>
                  <p class="text-sm text-gray-500">{{ guideData.departureDate }}</p>
                </div>
              </div>
            </div>
            <div class="flex gap-4">
              <el-button class="!rounded-button" type="primary" plain>
                <el-icon>
                  <Share/>
                </el-icon>
                分享
              </el-button>
              <el-button class="!rounded-button" type="primary" plain>
                <el-icon>
                  <Star/>
                </el-icon>
                收藏
              </el-button>
            </div>
          </div>
        </div>
        <!-- 基础信息概览 -->
        <div class="bg-white rounded-lg p-6 mb-6">
          <div class="grid grid-cols-3 gap-6">
            <div v-for="(item, index) in guideInfo" :key="index" class="flex items-center gap-3">
              <el-icon class="text-2xl text-primary-600">
                <component :is="item.icon"/>
              </el-icon>
              <div>
                <p class="text-sm text-gray-500">{{ item.label }}</p>
                <p class="font-medium">{{ item.value }}</p>
              </div>
            </div>
          </div>
        </div>
        <!-- 攻略内容 -->
        <div class="bg-white rounded-lg p-6 mb-6">
          <div class="prose max-w-none">
            <div v-html="guideData.content" class="mb-8">
            </div>
          </div>
        </div>
        <!-- 相关推荐 -->
        <div class="bg-white rounded-lg p-6">
          <h2 class="text-xl font-bold mb-6">相关推荐</h2>
          <swiper
              :modules="swiperModules"
              :slides-per-view="3"
              :space-between="20"
              :pagination="{ clickable: true }"
              class="mySwiper">
            <swiper-slide v-for="(item, index) in recommendations" :key="index" @click="toGuideView(item.id)">
              <div class="rounded-lg overflow-hidden cursor-pointer">
                <div class="aspect-[3/2] overflow-hidden">
                  <img :src="`${SERVER_ADDR}/scenicSpot/pic/${item.pic}`" class="w-full h-full object-cover"/>
                </div>
                <div class="p-4 border border-t-0 rounded-b-lg">
                  <h3 class="font-medium mb-2 line-clamp-2">{{ item.title }}</h3>
                  <p class="text-sm text-gray-500">{{ item.destination }} · {{ item.travelDays }}天</p>
                </div>
              </div>
            </swiper-slide>
          </swiper>
        </div>
      </div>
      <!-- 底部互动栏 -->
      <div class="fixed bottom-4 left-1/2 -translate-x-1/2 bg-white shadow-lg py-3 px-6 rounded-full z-40">
        <div class="flex items-center gap-8">
          <div class="flex items-center gap-6">
            <div class="flex items-center gap-3 cursor-pointer">
              <el-icon class="text-xl">
                <ChatDotRound/>
              </el-icon>
              <span>{{ guideData.comments.length }}</span>
            </div>
            <div class="flex items-center gap-3 cursor-pointer">
              <el-icon class="text-xl">
                <Star/>
              </el-icon>
              <span>{{ guideData.collects }}</span>
            </div>
          </div>
          <el-button type="primary"
                     class="!rounded-button whitespace-nowrap"
                     @click=showCommentsDialog()>
            写评论
          </el-button>
        </div>
      </div>
      <!-- 返回顶部 -->
      <el-backtop :right="40" :bottom="120"/>
      <!-- 图片预览 -->
      <el-image-viewer
          v-if="showImageViewer"
          :url-list="[previewImage]"
          @close="showImageViewer = false"
      />
      <!-- 评论面板 -->
      <el-drawer v-model="showComments" title="评论" size="50%">
        <div class="px-4">
          <div class="mb-4">
            <el-input
                v-model="commentContent"
                type="textarea"
                rows="3"
                placeholder="写下你的评论..."
            />
            <div class="text-right mt-2">
              <el-button type="primary" @click="submitComment">发表评论</el-button>
            </div>
          </div>
          <div class="space-y-4">
            <div v-for="comment in comments.list" :key="comment.id" class="border-b pb-4">
              <div class="flex items-center mb-2">
                <img :src="`${SERVER_ADDR}/category/pic/${comment.user.avatar}`" class="w-8 h-8 rounded-full"
                     :alt="comment.username"/>
                <span class="ml-2 font-medium">{{ comment.user.username }}</span>
              </div>
              <p class="text-gray-700">{{ comment.content }}</p>
              <p class="text-gray-500 text-sm mt-2">{{ comment.createTime }}</p>
            </div>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>
<script setup>
import {computed, ref, shallowRef, watch} from 'vue';
import {Swiper, SwiperSlide} from 'swiper/vue';
import {Pagination, Autoplay} from 'swiper/modules';
import {
  ArrowLeft,
  Share,
  Star,
  ChatDotRound,
  Location,
  Calendar,
  UserFilled,
  Wallet,
  Timer,
  Flag,
  Plus,
} from '@element-plus/icons-vue';
import {useTokenStore} from "@/stores/tokenStore.js";
import {useRoute, useRouter} from "vue-router";
import strategyApi from '@/api/strategyApi';
import commentApi from '@/api/commentApi';
import {ElMessage} from "element-plus";
import QuillEditor from "@/components/common/QuillEditor.vue";
import {Toolbar} from "@wangeditor/editor-for-vue";

const router = useRouter();
const route = useRoute();
const tokenStore = useTokenStore();
const headers = computed(() => {
  const token = tokenStore.tokenStr;
  return {
    token: token
  }
})
//服务器的地址
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
const swiperModules = [Pagination, Autoplay];

const showImageViewer = ref(false);
const previewImage = ref('');
const showComments = ref(false);
const commentContent = ref('');
const commentCount = ref(45);
// 用户评论
const addComment = ref({});

const openImagePreview = (image) => {
  previewImage.value = image;
  showImageViewer.value = true;
};
// 攻略
const guideData = ref({
  id: null,
  title: null,
  content: null,
  description: null,
  destination: null,
  travelDays: null,
  departureDate: null,
  numberOfTravelers: null,
  budgetRange: null,
  tripType: null,
  user: {
    id: null,
    username: null,
    password: null,
    payPassword: null,
    realname: null,
    avatar: null,
    sex: null,
    isCard: null,
    phone: null,
    email: null,
    regTime: null,
    money: null,
    status: null,
  },
  comments: [],
  collects: null,
  images: null,
  recommendations: null,
  createdAt: null,
  updatedAt: null,
  pic: null,
});
const guideInfo = ref();
const recommendations = ref();
// 评论数据
const comments = ref([]);
// 显示添加评论弹窗
const showWriteGuide = ref(false);
// 新增攻略
const newGuide = ref({
  title: '',
  content: '',
  description: '',
  userId: '',
  destination: '',
  travelDays: '',
  departureDate: '',
  numberOfTravelers: '',
  budgetRange: '',
  tripType: '',
  pic: '',
});
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 设置wangEditor的内容
const mode = ref('default');
//工具栏的设置
const toolbarConfig = {}
// 图片显示
const imageUrl = ref();

// 跳转到攻略详情页
const toGuideView = (id)=>{
  router.push({
    path: '/user/strategy',
    query: {
      id: id,
      date:new Date().getTime()
    }
  });
}
// 删除图片
const handleRemove = () => {
  imageUrl.value = '';
  newGuide.value.pic = null;
}
// 显示写攻略弹窗
const showWriteGuideDisalog = () => {
  // 判断用户是否登录，如果没有则跳转到登录界面
  if (tokenStore.tokenStr != null) {
    showWriteGuide.value = true;
  } else {
    ElMessage.warning("请先登录")
    router.push('/login');
  }

};
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('只能上传jpg格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片大小不能超过1MB')
    return false
  }
  return true
}
//图片上传成功的钩子函数
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 10000) {
    ElMessage.success(response.msg);
    imageUrl.value = `${SERVER_ADDR.value}/scenicSpot/pic/${response.data}`;
    newGuide.value.pic = response.data;
  } else {
    ElMessage.error(response.msg);
  }
}
const handleClose = () => {
    showWriteGuide.value = false;
    newGuide.value = {
      title: '',
      content: '',
      description: '',
      userId: '',
      destination: '',
      travelDays: '',
      departureDate: '',
      numberOfTravelers: '',
      budgetRange: '',
      tripType: '',
      pic: '',
    };
    imageUrl.value = '';
    this.$refs.md.wangEditor.txt.html('<p><br></p>')
  };
const handleSubmit = () => {
    if (!newGuide.value.title ||
        !newGuide.value.destination ||
        !newGuide.value.travelDays ||
        !newGuide.value.tripType ||
        !newGuide.value.content ||
        !newGuide.value.pic ||
        !newGuide.value.numberOfTravelers ||
        !newGuide.value.budgetRange ||
        !newGuide.value.departureDate
    ) {
      ElMessage.warning('请填写完整信息');
      return;
    }

  // 提交攻略内容
    strategyApi.insert(newGuide.value)
        .then(resp => {
          if (resp.code == 10000) {
            ElMessage.success(resp.msg);
            handleClose();
            ElMessage.success('发布成功,请在我的攻略模块查看');
          }
        })
  };
// 用户评论
const submitComment = () => {
  if (!commentContent.value.trim()) return;

  addComment.value = {
    type: 1,
    parentId: 0,
    strategyId: guideData.value.id,
    content: commentContent.value,
    createTime: new Date().toLocaleString(),
    status: 0,
  };
  commentApi.insert(addComment.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          commentContent.value = '';
          getComments();
        }

      })
};
// 显示用户评论面板
const showCommentsDialog = () => {
  // 判断用户是否登录
  if (tokenStore.tokenStr != null) {
    showComments.value = true;
    getComments();
  } else {
    ElMessage.warning('请先登录');
    router.push('/login');
  }
};
// 查询当前页面的数据
const selectById = () => {
  let id = route.query.id;
  console.log(id)
  strategyApi.selectById(id)
      .then(resp => {
        guideData.value = resp.data;
        guideInfo.value = [
          {label: '目的地', value: guideData.value.destination, icon: 'Location'},
          {label: '行程天数', value: guideData.value.travelDays, icon: 'Timer'},
          {label: '出发日期', value: guideData.value.departureDate, icon: 'Calendar'},
          {label: '出行人数', value: guideData.value.numberOfTravelers, icon: 'UserFilled'},
          {label: '预算范围', value: `¥${guideData.value.budgetRange}`, icon: 'Wallet'},
          {label: '旅行类型', value: guideData.value.tripType, icon: 'Flag'}
        ];

      })
}
// 查询该用户的其他攻略
const getStrategyByUser = () => {
  const conditon = {
    userId: guideData.value.user.id
  }
  strategyApi.selectAll(conditon, 1, 4)
      .then(resp => {
        if (resp.code == 10000) {
          recommendations.value = resp.data.list;
          // 去除重复，如果有跟当前攻略重复的，就删除
          recommendations.value.forEach((item, index) => {
            if (item.id == route.query.id) {
              recommendations.value.splice(index, 1);
            }
          });
        }
      })
}
// 查询所有评论
const getComments = () => {
  commentApi.selectAll(route.query.id)
      .then(resp => {
        comments.value = resp.data;
      })
}
// 监听路由参数变化
watch(
    () => route.query.id,
    (newId) => {
      selectById();
      getStrategyByUser();
    },
    { immediate: true } // 立即执行一次，替代 created 钩子
);
selectById();
getStrategyByUser();

</script>

<style scoped>
.prose {
  max-width: 100%;
}

.prose h2 {
  margin-top: 2rem;
  margin-bottom: 1rem;
  font-size: 1.5rem;
  font-weight: 600;
  color: #1a1a1a;
}

.prose p {
  margin-bottom: 1.5rem;
  line-height: 1.75;
  color: #4a4a4a;
}

.swiper {
  width: 100%;
  height: 100%;
  padding-bottom: 2rem;
}

:deep(.swiper-pagination) {
  bottom: 0;
}

:deep(.swiper-pagination-bullet) {
  background: #4a4a4a;
}

:deep(.swiper-pagination-bullet-active) {
  background: #1a1a1a;
}

.avatar-uploader,
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px dotted #dcdfe6;
  border-radius: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
}
</style>

